<template>
  <div class="positions-container">
    <el-card class="positions-card">
      <template #header>
        <div class="card-header">
          <span>岗位管理</span>
          <el-button type="primary" @click="handleAdd">新增岗位</el-button>
        </div>
      </template>

      <el-form :inline="true" class="search-form">
        <el-form-item label="岗位名称">
          <el-input v-model="searchForm.name" placeholder="请输入岗位名称" clearable />
        </el-form-item>
        <el-form-item label="所属部门" style="width: 250px;">
          <el-tree-select
            v-model="searchForm.departmentId"
            :data="departmentOptions"
            :props="{
              value: 'id',
              label: 'name',
              children: 'children'
            }"
            placeholder="请选择所属部门"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table :data="positionList" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="岗位名称" />
        <el-table-column prop="code" label="岗位编码" width="120" />
        <el-table-column prop="departmentId" label="所属部门" width="180">
          <template #default="{ row }">
            {{ getDepartmentName(row.departmentId) }}
          </template>
        </el-table-column>
        <el-table-column prop="level" label="职级" width="100">
          <template #default="{ row }">
            <el-tag>{{ row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 岗位表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增岗位' : '编辑岗位'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="positionForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="岗位名称" prop="name">
          <el-input v-model="positionForm.name" placeholder="请输入岗位名称" />
        </el-form-item>
        <el-form-item label="岗位编码" prop="code">
          <el-input v-model="positionForm.code" placeholder="请输入岗位编码" />
        </el-form-item>
        <el-form-item label="所属部门" prop="departmentId">
          <el-tree-select
            v-model="positionForm.departmentId"
            :data="departmentOptions"
            :props="{
              value: 'id',
              label: 'name',
              children: 'children'
            }"
            placeholder="请选择所属部门"
          />
        </el-form-item>
        <el-form-item label="职级" prop="level">
          <el-select v-model="positionForm.level" placeholder="请选择职级">
            <el-option label="P1" value="P1" />
            <el-option label="P2" value="P2" />
            <el-option label="P3" value="P3" />
            <el-option label="P4" value="P4" />
            <el-option label="P5" value="P5" />
            <el-option label="P6" value="P6" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="positionForm.description"
            type="textarea"
            placeholder="请输入岗位描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { getPositionPage, addPosition, updatePosition, deletePosition, togglePositionStatus } from '@/api/positions'
import { getDepartmentList } from '@/api/departments'

interface Position {
  id: number
  name: string
  code: string
  department: string
  departmentId: number
  level: string
  status: 'active' | 'inactive'
  description: string
  createTime: string
}

interface Department {
  id: number
  name: string
  children?: Department[]
}

const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const formRef = ref<FormInstance>()

const searchForm = reactive({
  name: null,
  departmentId: null as number | null
})

const positionForm = reactive({
  id: 0,
  name: '',
  code: '',
  departmentId: null as number | null,
  level: '',
  description: ''
})

const rules = {
  name: [{ required: true, message: '请输入岗位名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入岗位编码', trigger: 'blur' }],
  departmentId: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
  level: [{ required: true, message: '请选择职级', trigger: 'change' }]
}

const positionList = ref<Position[]>([])
const departmentOptions = ref<Department[]>([])
const departmentList = ref<Department[]>([])

const getDepartmentName = (departmentId: number) => {
  const department = departmentList.value.find(dep => dep.id === departmentId)
  return department?.name || '未知部门'
}

async function loadPositions() {
  loading.value = true
  try {
    const response = await getPositionPage({
      current: currentPage.value,
      size: pageSize.value,
      name: searchForm.name,
      departmentId: searchForm.departmentId
    })
    positionList.value = response.records
    total.value = response.total
  } catch (error) {
    console.error('获取岗位列表失败:', error)
    ElMessage.error('获取岗位列表失败')
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  currentPage.value = 1
  loadPositions()
}

function handleReset() {
  searchForm.name = ''
  searchForm.departmentId = null
  handleSearch()
}

function resetForm() {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(positionForm, {
    id: 0,
    name: '',
    code: '',
    departmentId: null,
    level: '',
    description: ''
  })
}

function handleAdd() {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

function handleEdit(row: Position) {
  dialogType.value = 'edit'
  Object.assign(positionForm, {
    id: row.id,
    name: row.name,
    code: row.code,
    departmentId: row.departmentId,
    level: row.level,
    description: row.description
  })
  dialogVisible.value = true
}

async function handleToggleStatus(row: Position) {
  const action = row.status === 'active' ? '禁用' : '启用'
  try {
    await ElMessageBox.confirm(
      `确定要${action}该岗位吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    await togglePositionStatus(row.id)
    ElMessage.success(`${action}成功`)
    loadPositions()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('状态切换失败:', error)
      ElMessage.error(`${action}失败`)
    }
  }
}

async function handleDelete(row: Position) {
  try {
    await ElMessageBox.confirm(
      '确定要删除该岗位吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    await deletePosition(row.id)
    ElMessage.success('删除成功')
    loadPositions()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

async function handleSubmit() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (dialogType.value === 'add') {
      await addPosition(positionForm)
    } else {
      await updatePosition(positionForm)
    }
    
    ElMessage.success(dialogType.value === 'add' ? '新增成功' : '编辑成功')
    dialogVisible.value = false
    loadPositions()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error(dialogType.value === 'add' ? '新增失败' : '编辑失败')
  }
}

function handleSizeChange(val: number) {
  pageSize.value = val
  loadPositions()
}

function handleCurrentChange(val: number) {
  currentPage.value = val
  loadPositions()
}

// 将平铺的部门数据转换为树形结构
function buildDepartmentTree(departments: any[]): any[] {
  const departmentMap = new Map()
  const tree: any[] = []
  
  // 首先将所有部门存入map
  departments.forEach(dept => {
    departmentMap.set(dept.id, { ...dept, children: [] })
  })
  
  // 构建树形结构
  departments.forEach(dept => {
    const node = departmentMap.get(dept.id)
    if (dept.parentId) {
      const parent = departmentMap.get(dept.parentId)
      if (parent) {
        parent.children.push(node)
      }
    } else {
      tree.push(node)
    }
  })
  
  return tree
}

// 加载部门数据
async function loadDepartments() {
  try {
    const response = await getDepartmentList()
    departmentList.value = response
    departmentOptions.value = buildDepartmentTree(response)
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  }
}

onMounted(() => {
  // 初始加载
  loadDepartments()
  loadPositions()
})

</script>

<style scoped>
.positions-container {
  padding: 20px;
}

.positions-card {
  background: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background: var(--el-fill-color-blank);
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
}
</style>